package com.mark.common;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * Created by Mark on 2018/3/23.
 *Guava工具缓存工具类
 */
@Slf4j
public class TokenCache {

    public static final String TOKEN_PREFIX = "token_";

    private static LoadingCache<String,String> localCache = CacheBuilder.newBuilder()
            .initialCapacity(1000)//initialCapacity:缓存的初始化容量
            .maximumSize(10000)//maximumSize:缓存的最大容量//LRU算法
            .expireAfterAccess(12, TimeUnit.MINUTES) //expireAfterAccess:设置有效期
            .build(new CacheLoader<String, String>() {//默认的数据加载实现,当调用get取值的时候,如果key没有对应的值,就调用这个方法进行加载.
                @Override
                public String load(String s) throws Exception {
                    return "null";
                }
            });

    public static void setKey(String key,String value){
        localCache.put(key,value);//放到本地缓存
    }

    public static String getKey(String key){
        String value = null;
        try {
            value = localCache.get(key);
            if("null".equals(value)){
                return null;
            }
            return value;
        }catch (Exception e){
            log.error("localCache getKey error",e.getMessage());
        }
        return null;
    }

}
